package org.hackystat.devcathlon.engine.db.hibernate;

import java.io.File;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Hibernate Util class.
 * 
 * @author Anthony Du 
 *
 */
public class HibernateUtil {
  /** The Session Factory. */
  private static SessionFactory sessionFactory;
  /** Configuration path. */
  private static String configPath = System.getProperty("user.home") 
                                        + "/.hackystat/devcathlon/hibernate/hibernate.cfg.xml";
  /** Configuration object. */
  private static Configuration config;
  
  static {
    try {
      // Creates a new Configuration based off of hibernate.cfg.xml
      config = new Configuration().configure(new File(configPath)); 
      // Add resource mappings here...
      config.addResource("org/hackystat/devcathlon/engine/user/User.hbm.xml");
      config.addResource("org/hackystat/devcathlon/engine/profile/Profile.hbm.xml");
      config.addResource("org/hackystat/devcathlon/engine/team/Team.hbm.xml");
      config.addResource("org/hackystat/devcathlon/engine/project/TeamProject.hbm.xml");
      config.addResource("org/hackystat/devcathlon/engine/match/Match.hbm.xml");
      config.addResource("org/hackystat/devcathlon/engine/event/Event.hbm.xml");
      config.addResource("org/hackystat/devcathlon/engine/event/EventScore.hbm.xml");
      config.addResource("org/hackystat/devcathlon/engine/commentary/Comment.hbm.xml");
      // Creates the session factory using the configuration
      sessionFactory = config.buildSessionFactory();
      // include map relations and other configurations here...
      System.out.println("Initialized SessionFactory.");
    }
    catch (Throwable ex) {
      System.err.println("Initial SessionFactory creation failed." + ex);
      throw new ExceptionInInitializerError(ex);
    }
  }
  
  /**
   * Returns the current session factory.
   * @return The current session factory.
   */
  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }
  
  /**
   * Closes the session factory.
   */
  public static void shutdown() {
    getSessionFactory().close();
  }
}
